import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft, Calendar, Clock, CheckCircle, Circle, Eye } from 'lucide-react'
import LoadingSpinner from '../components/LoadingSpinner'
import { apiRequest } from '../services/api'

interface TaskInstance {
  id: string
  title: string
  description?: string
  dueDate: string
  priority: string
  category: string
  status: string
  completed: boolean
  createdAt: string
  recurringTaskId: string
}

interface RecurringTask {
  id: string
  title: string
  description?: string
  recurringType: string
  recurringPattern: string | null
  isActive: boolean
}

export default function RecurringTaskInstancesPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [recurringTask, setRecurringTask] = useState<RecurringTask | null>(null)
  const [instances, setInstances] = useState<TaskInstance[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [filter, setFilter] = useState<'all' | 'pending' | 'completed'>('all')

  useEffect(() => {
    if (id) {
      loadData()
    }
  }, [id])

  const loadData = async () => {
    try {
      setIsLoading(true)
      
      // 加载重复任务信息
      const taskData = await apiRequest<RecurringTask>(`/recurring/${id}`)
      setRecurringTask(taskData)

      // 加载任务实例
      const instancesData = await apiRequest<TaskInstance[]>(`/recurring/${id}/instances`)
      setInstances(instancesData)
    } catch (error) {
      console.error('加载数据失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleToggleComplete = async (instanceId: string, completed: boolean) => {
    try {
      await apiRequest(`/tasks/${instanceId}/toggle`, {
        method: 'PATCH'
      })

      setInstances(prev => prev.map(instance => 
        instance.id === instanceId 
          ? { ...instance, completed: !completed }
          : instance
      ))
    } catch (error) {
      console.error('更新任务状态失败:', error)
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'todo': return 'bg-gray-50 text-gray-700 border-gray-200'
      case 'in_progress': return 'bg-blue-50 text-blue-700 border-blue-200'
      case 'review': return 'bg-yellow-50 text-yellow-700 border-yellow-200'
      case 'done': return 'bg-green-50 text-green-700 border-green-200'
      default: return 'bg-gray-50 text-gray-700 border-gray-200'
    }
  }

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'todo': return '待办'
      case 'in_progress': return '进行中'
      case 'review': return '审核中'
      case 'done': return '已完成'
      default: return status
    }
  }

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'P0': return 'bg-red-50 text-red-700 border-red-200'
      case 'P1': return 'bg-orange-50 text-orange-700 border-orange-200'
      case 'P2': return 'bg-blue-50 text-blue-700 border-blue-200'
      case 'P3': return 'bg-gray-50 text-gray-700 border-gray-200'
      default: return 'bg-gray-50 text-gray-700 border-gray-200'
    }
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const taskDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
    
    if (taskDate.getTime() === today.getTime()) {
      return '今天'
    } else if (taskDate.getTime() === today.getTime() - 24 * 60 * 60 * 1000) {
      return '昨天'
    } else if (taskDate.getTime() === today.getTime() + 24 * 60 * 60 * 1000) {
      return '明天'
    } else {
      return date.toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric'
      })
    }
  }

  const filteredInstances = instances.filter(instance => {
    switch (filter) {
      case 'pending': return !instance.completed
      case 'completed': return instance.completed
      default: return true
    }
  })

  const getRecurringTypeLabel = (type: string) => {
    switch (type) {
      case 'daily': return '每日'
      case 'weekly': return '每周'
      case 'monthly': return '每月'
      case 'yearly': return '每年'
      default: return type
    }
  }

  const getRecurringPatternLabel = (pattern: string | null | undefined) => {
    if (!pattern || typeof pattern !== 'string') return ''
    
    // 常见模式的中文映射
    const patternMap: { [key: string]: string } = {
      'every_day': '每天',
      'every_week': '每周',
      'every_month': '每月',
      'every_year': '每年',
      'every_monday': '每周一',
      'every_tuesday': '每周二',
      'every_wednesday': '每周三',
      'every_thursday': '每周四',
      'every_friday': '每周五',
      'every_saturday': '每周六',
      'every_sunday': '每周日',
      'every_weekday': '每个工作日',
      'every_weekend': '每个周末',
      'every_2_days': '每两天',
      'every_3_days': '每三天',
      'every_2_weeks': '每两周',
      'every_month_on_1st': '每月1号',
      'every_month_on_15th': '每月15号',
      'every_month_last_day': '每月最后一天',
      'every_quarter': '每季度',
      'every_6_months': '每半年'
    }

    // 直接匹配
    if (patternMap[pattern]) {
      return patternMap[pattern]
    }

    // 动态解析常见格式
    if (pattern.startsWith('every_')) {
      const daysMatch = pattern.match(/every_(\d+)_days?/)
      if (daysMatch) {
        return `每${daysMatch[1]}天`
      }

      const weeksMatch = pattern.match(/every_(\d+)_weeks?/)
      if (weeksMatch) {
        return `每${weeksMatch[1]}周`
      }

      const monthsMatch = pattern.match(/every_(\d+)_months?/)
      if (monthsMatch) {
        return `每${monthsMatch[1]}个月`
      }

      const yearsMatch = pattern.match(/every_(\d+)_years?/)
      if (yearsMatch) {
        return `每${yearsMatch[1]}年`
      }
    }

    // 如果没有匹配到，返回原始值
    return pattern
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-theme-bg-secondary flex items-center justify-center">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* 顶部导航 */}
      <div className="sticky top-0 z-10 bg-theme-bg/95 backdrop-blur-sm border-b border-theme-border/60 shadow-sm">
        <div className="flex items-center justify-between px-4 sm:px-6 py-4">
          <button
            onClick={() => navigate('/recurring')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">任务实例</h1>
          <div className="w-10"></div>
        </div>
      </div>

      <div className="px-4 sm:px-6 pb-24 space-y-6 max-w-4xl mx-auto py-6">
        {/* 重复任务信息 */}
        {recurringTask && (
          <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-6 shadow-sm">
            <div className="flex items-start gap-4">
              <div className="flex-shrink-0 mt-1">
                <div className={`w-3 h-3 rounded-full ${
                  recurringTask.isActive ? 'bg-green-500' : 'bg-gray-400'
                }`}></div>
              </div>
              <div className="flex-1">
                <h2 className="text-xl font-semibold text-theme-text mb-2">{recurringTask.title}</h2>
                {recurringTask.description && (
                  <p className="text-theme-text-secondary mb-3">{recurringTask.description}</p>
                )}
                <div className="flex items-center gap-4 text-sm text-theme-text-muted">
                  <div className="flex items-center gap-1">
                    <Calendar size={14} />
                    <span>重复: {recurringTask.recurringPattern ? getRecurringPatternLabel(recurringTask.recurringPattern) : getRecurringTypeLabel(recurringTask.recurringType)}</span>
                  </div>
                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                    recurringTask.isActive 
                      ? 'bg-green-50 text-green-700 border border-green-200' 
                      : 'bg-gray-50 text-gray-700 border border-gray-200'
                  }`}>
                    {recurringTask.isActive ? '活跃' : '暂停'}
                  </span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 筛选器 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-4 shadow-sm">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-theme-text">筛选:</span>
            <div className="flex gap-2">
              {[
                { key: 'all', label: '全部' },
                { key: 'pending', label: '待完成' },
                { key: 'completed', label: '已完成' }
              ].map(item => (
                <button
                  key={item.key}
                  onClick={() => setFilter(item.key as any)}
                  className={`px-3 py-1 text-sm rounded-full transition-all ${
                    filter === item.key
                      ? 'bg-blue-100 text-blue-700 border border-blue-200'
                      : 'bg-theme-bg-secondary text-theme-text-secondary hover:bg-theme-bg-tertiary border border-theme-border/30'
                  }`}
                >
                  {item.label}
                </button>
              ))}
            </div>
            <div className="ml-auto text-sm text-theme-text-muted">
              共 {filteredInstances.length} 个实例
            </div>
          </div>
        </div>

        {/* 任务实例列表 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 shadow-sm">
          <div className="p-5 border-b border-theme-border/60">
            <h3 className="text-lg font-semibold text-theme-text">任务实例列表</h3>
          </div>

          {filteredInstances.length === 0 ? (
            <div className="p-12 text-center">
              <Calendar size={48} className="mx-auto text-slate-300 mb-4" />
              <h3 className="text-lg font-medium text-theme-text mb-2">暂无实例</h3>
              <p className="text-theme-text-muted">该重复任务还没有生成实例</p>
            </div>
          ) : (
            <div className="divide-y divide-theme-border/30">
              {filteredInstances.map((instance) => (
                <div key={instance.id} className="p-5 hover:bg-theme-bg-secondary/50 transition-colors">
                  <div className="flex items-start gap-4">
                    {/* 完成状态 */}
                    <button
                      onClick={() => handleToggleComplete(instance.id, instance.completed)}
                      className="flex-shrink-0 mt-1 text-theme-text-secondary hover:text-blue-600 transition-colors"
                    >
                      {instance.completed ? (
                        <CheckCircle size={20} className="text-green-600" />
                      ) : (
                        <Circle size={20} />
                      )}
                    </button>

                    {/* 任务信息 */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between mb-2">
                        <h4 className={`font-medium ${
                          instance.completed 
                            ? 'text-theme-text-muted line-through' 
                            : 'text-theme-text'
                        }`}>
                          {instance.title}
                        </h4>
                        <div className="flex items-center gap-2">
                          <span className={`px-2 py-1 text-xs font-medium rounded-full border ${getPriorityColor(instance.priority)}`}>
                            {instance.priority}
                          </span>
                          <span className={`px-2 py-1 text-xs font-medium rounded-full border ${getStatusColor(instance.status)}`}>
                            {getStatusLabel(instance.status)}
                          </span>
                        </div>
                      </div>

                      {instance.description && (
                        <p className="text-sm text-theme-text-secondary mb-2 line-clamp-2">
                          {instance.description}
                        </p>
                      )}

                      <div className="flex items-center gap-4 text-sm text-theme-text-muted">
                        <div className="flex items-center gap-1">
                          <Calendar size={14} />
                          <span>截止: {formatDate(instance.dueDate)}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Clock size={14} />
                          <span>创建: {formatDate(instance.createdAt)}</span>
                        </div>
                      </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex-shrink-0">
                      <button
                        onClick={() => navigate(`/task/${instance.id}`)}
                        className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
                        title="查看详情"
                      >
                        <Eye size={16} />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
